package com.mgface.framework.AIOServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;

/**
 * Hello world!
 *
 */
public class AIOServer {
	public static final int port = 8888;
	public Logger log = Logger.getLogger(this.getClass().getSimpleName());
	private AsynchronousServerSocketChannel server;

	public AIOServer() throws IOException{
		server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
	}
	
	public void startWithFuture(){
		log.info(()->"开始监听8888。。。。");
		Future<AsynchronousSocketChannel> future = server.accept();
		try {
			log.info(()->"开始Get1。。。。");
			AsynchronousSocketChannel socket = future.get();
			log.info(()->"开始Get2。。。。");
			ByteBuffer buffer = ByteBuffer.allocate(8*1024);
			buffer.clear();
			socket.read(buffer).get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
			buffer.flip();
			log.info(()->"接受到的数据为:"+new String(buffer.array()));
			log.info(()->"当前线程为:"+Thread.currentThread().getName());
		} catch (InterruptedException | ExecutionException | TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void startWithCompletionHandler() throws Exception{
		log.info(()->"开始监听端口8888....");
		server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
			@Override
			public void completed(AsynchronousSocketChannel result, Object attachment) {
				log.info(()->"当前线程为:"+Thread.currentThread().getName());
				server.accept(null, this);//再次接受请求  
				try {
					Thread.sleep(10_000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                log.info(()->"start......");
                ByteBuffer buffer = ByteBuffer.allocate(8*1024);
                Future<Integer> future = null;
                try {  
                    buffer.clear();  
                    future = result.read(buffer);
                    future.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
                    buffer.flip();
                    String res = new String(buffer.array());
                    log.info(()->"接受到的数据为:"+res);
                    String reciveMsg = "你好:"+ res;
                    result.write(ByteBuffer.wrap(reciveMsg.getBytes()));
                } catch (InterruptedException | ExecutionException e) {  
                    System.out.println(e.toString());  
                } catch (TimeoutException e) {  
                    e.printStackTrace();  
                } finally {  
                    try {  
                        result.close();
                        future.cancel(true);
                       // server.accept(null, this);  
                    } catch (Exception e) {  
                        System.out.println(e.toString());  
                    }  
                }  
                log.info(()->"end......");
			}
			@Override
			public void failed(Throwable exc, Object attachment) {
				log.info(()->"error:"+exc.getMessage());
				
			}
		});
		 // 主线程继续自己的行为  
        while (true) {  
            log.info(()->"main thread");  
            TimeUnit.SECONDS.sleep(10);
        }
	}
	public static void main(String[] args) throws Exception {
		//new AIOServer().startWithFuture();
		new AIOServer().startWithCompletionHandler();
	}
}
